import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Login from "../views/Login.vue";
import NotFound from "../views/404.vue"
import User from "../views/SysMng/User.vue"
import Menu from "../views/SysMng/Menu.vue"
import Dept from "../views/SysMng/Dept.vue"
import Role from "../views/SysMng/Role.vue"
import Log from "../views/SysMng/Log.vue"
import Intro from "../views/SysMng/Intro.vue"

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    children: [
      { path: '', component: Intro, name: '系统介绍' },
      { path: "sys/user", name: "用户管理", component: User},
      { path: "sys/menu",name: "菜单管理",component: Menu},
      { path: 'sys/dept', component: Dept, name: '机构管理' },
      { path: 'sys/role', component: Role, name: '角色管理' },
      { path: 'sys/log', component: Log, name: '日志管理' }
    ]
  },
  {
    path: "/Login",
    name: "login",
    component: Login
  },
  {
    path: "/404",
    name: "NotFound",
    component: NotFound
  }
];

const router = new VueRouter({
  routes
});

// 添加路由导航守卫  全局前置守卫
router.beforeEach((to, from, next) => {
  // 登录界面登录成功之后，把信息保存在会话
  // 存在时间为会话生命周期，页面关闭及失效
  // let token = Cookies.get('token') 正式环境一般都用token来判断
  let user = sessionStorage.getItem("user");
  if (to.path === "/login") {
    // 如果访问的是登录页面，如果会话信息以及存在，代表以及登录过，跳转到登录页面
    if (user) {
      next({ path: "/" });
    } else {
      next();
    }
  } else {
    // 如果访问的不是登录界面，且会话信息不存在，则表示未登录，跳到登录页面去登录
    if (!user) {
      next({ path: "/" });
    } else {
      next();
    }
  }
});

export default router;
